package com.houzehui.user.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.houzehui.common.vo.LoginUserInfo;
import com.houzehui.user.config.MsgResult;
import com.houzehui.user.entity.User;
import com.houzehui.user.service.IUserService;
import com.houzehui.user.utils.JwtUtils;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author houzehui
 * @since 2022-04-26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService iUserService;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("login")
    public MsgResult login(User user){
        String key="8d3a28ccde429209df6fd235d60fb440";

        System.err.println(user);
        //判断手机号不能为空
        if(!StringUtils.hasText(user.getPhone())){
            return MsgResult.fail("手机号不能为空");
        }
        //判断密码不能为空
        if(!StringUtils.hasText(user.getPassword())){
            return MsgResult.fail("密码不能为空");
        }

        if(user.getCode()!=null){
            String rediscode = (String) redisTemplate.opsForValue().get(user.getKeys());
            if (!user.getCode().equals(rediscode)){
                return MsgResult.fail("验证码错误");
            }
        }
        User userInfo = iUserService.getOne(new QueryWrapper<User>().eq("phone", user.getPhone()));
        if(userInfo==null){
            return MsgResult.fail("手机号不存在");
        }
//        //md5加密的密码
//        String pwd = SecureUtil.md5(user.getPassword());
//        System.err.println("加密:"+pwd);
//
//        String password=pwd+username.getSalt();
//        //加盐
//        String userpwd = DigestUtils.md5DigestAsHex(password.getBytes());
//        System.out.println("salt:"+userpwd);
        String pwd = SecureUtil.md5( user.getPassword()+ key + "05b0f203987e49d2b72b20b95e0e57d9");


        if(!userInfo.getPassword().equals(pwd)){
            if(userInfo.getLoginNum()>=3){
                Date date = new Date();
                Date endLoginTime = userInfo.getEndLoginTime();
                long between = DateUtil.between(date, endLoginTime, DateUnit.MINUTE);
                long a=30-between;
                System.err.println("剩余时间:"+a);
                if (a<=0){
                    userInfo.setLoginNum(0);
                    userInfo.setStatus(0);
                    iUserService.updateById(userInfo);
                }else{
                    return MsgResult.fail("密码输入错误3次,用户已禁用,请"+a+"分钟后在试");
                }
            }

            Integer loginNum = userInfo.getLoginNum()+1;
            userInfo.setLoginNum(loginNum);
            userInfo.setEndLoginTime(new Date());

            iUserService.updateById(userInfo);

            if(userInfo.getLoginNum()>=3){
                userInfo.setStatus(1);
                iUserService.updateById(userInfo);
                return MsgResult.fail("密码输入错误3次,用户已禁用,半小时后在尝试");

            }
            return MsgResult.fail("密码错误");
        }

        userInfo.setLoginNum(0);
        iUserService.updateById(userInfo);

        LoginUserInfo loginUserInfo = new LoginUserInfo();

        loginUserInfo.setId(userInfo.getId());
        loginUserInfo.setUsername(userInfo.getUsername());

        //jwt
        String token = jwtUtils.createToken(JSON.toJSONString(loginUserInfo));

        return MsgResult.succeed(token);

    }

    @RequestMapping("getPic")
    public void getCode(HttpServletResponse response,String keys,User user) throws IOException {
        //定义验证码的长度 宽度 验证码的长度
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(100, 60, 4, 10);
        String code = circleCaptcha.getCode();
        System.err.println("获取的验证码"+code);


        redisTemplate.opsForValue().set(keys,code,60, TimeUnit.SECONDS);


        //发送到浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        circleCaptcha.write(outputStream);
        outputStream.close();
    }

    @GetMapping("getKeys")
    public String getKeys(){
        String uuid = UUID.randomUUID().toString();
        return uuid;
    }

    public static void main(String[] args) {
        String key="8d3a28ccde429209df6fd235d60fb440";
        String s = SecureUtil.md5("123456" + key + "05b0f203987e49d2b72b20b95e0e57d9");
        System.out.println(s);
    }

}
